"use client";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { useRef, useState } from "react";
import Image from "next/image";

export default function UploadImage() {
  const [isLoading, setLoading] = useState(false);
  const [imageUrls, setImageUrls] = useState<string[]>([]);
  const fileInputRef = useRef<HTMLInputElement>(null);
  return (
    <div className="bg-zinc-200 h-screen pt-10 flex flex-col">
      <h1 className="text-3xl font-bold text-center pt-10 capitalize">
        Create your gallery
      </h1>
      <div className="flex flex-wrap gap-1 p-5 bg-white w-[650px] min-h-[300px] mx-auto mt-6 mb-10 rounded-md shadow-sm">
        {imageUrls.map((url, index) => (
          <div key={index} className="relative flexx-1 basis-[300px] h-[200px]">
            <Image
              key={index}
              src={url}
              alt={`Uploaded Image ${index}`}
              className="w-full h-full object-cover rounded-md"
              fill
              loader={({ src, width }) => {
                // return `${src}&img-format=webp&w=${width}`
                return src;
              }}
            />
          </div>
        ))}
      </div>
      <div className="flex justify-center">
        <Input
          type="file"
          accept="image/*"
          ref={fileInputRef}
          onChange={(e) => {
            const file = e.target.files?.[0];
            if (file) {
              // Upload the file to the server
              // 以下两种写法的区别是：第一种写法是直接将文件上传到服务器，而第二种写法是将文件上传到服务器后，再将服务器返回的URL保存到imageUrls数组中
              // setImageUrls([...imageUrls, URL.createObjectURL(file)]);
              setImageUrls((prev) => [...prev, URL.createObjectURL(file)]);
              console.log("🚀 ~ UploadImage ~ file:", file);
            }
          }}
          disabled={isLoading}
          className="hidden"
        />
        <Button onClick={() => fileInputRef.current?.click()}>
          Upload Image
        </Button>
      </div>
    </div>
  );
}
